package cn.iocoder.yudao.module.esim.service.esproduct;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.esim.enums.esproduct.EsProductTypeEnum;
import cn.iocoder.yudao.module.esim.framework.config.ESimBusinessConfig;
import cn.iocoder.yudao.module.esim.service.esapi.IESimThirtyApiService;
import cn.iocoder.yudao.module.esim.service.esapi.model.ProductRes;
import cn.iocoder.yudao.module.esim.util.ESimUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.esim.controller.admin.esproduct.vo.*;
import cn.iocoder.yudao.module.esim.dal.dataobject.esproduct.EsProductDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.esim.dal.mysql.esproduct.EsProductMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.esim.enums.ErrorCodeConstants.*;

/**
 * eSim商品 Service 实现类
 *
 * @author 超管
 */
@Service
@Validated
@Slf4j
public class EsProductServiceImpl implements EsProductService {

    @Resource
    private EsProductMapper esProductMapper;
    @Resource
    private IESimThirtyApiService simThirtyApiService;
    @Resource
    private ESimBusinessConfig eSimBusinessConfig;

    @Override
    public String createEsProduct(EsProductSaveReqVO createReqVO) {
        // 插入
        EsProductDO esProduct = BeanUtils.toBean(createReqVO, EsProductDO.class);
        esProductMapper.insert(esProduct);
        // 返回
        return esProduct.getId();
    }

    @Override
    public void updateEsProduct(EsProductSaveReqVO updateReqVO) {
        // 校验存在
        validateEsProductExists(updateReqVO.getId());
        // 更新
        EsProductDO updateObj = BeanUtils.toBean(updateReqVO, EsProductDO.class);
        esProductMapper.updateById(updateObj);
    }

    @Override
    public void deleteEsProduct(String id) {
        // 校验存在
        validateEsProductExists(id);
        // 删除
        esProductMapper.deleteById(id);
    }

    private void validateEsProductExists(String id) {
        if (esProductMapper.selectById(id) == null) {
            throw exception(ES_PRODUCT_NOT_EXISTS);
        }
    }

    @Override
    public EsProductDO getEsProduct(String id) {
        return esProductMapper.selectById(id);
    }

    @Override
    public PageResult<EsProductDO> getEsProductPage(EsProductPageReqVO pageReqVO) {
        return esProductMapper.selectPage(pageReqVO);
    }


    /**
     * 从api同步产品
     */
    @Override
    public void synProductFromApi() {
        final Boolean enableSynProduct = eSimBusinessConfig.getEnableSynProduct();
        log.info("从api同步产品-开始, enableSynProduct = {}", enableSynProduct);
        if (!enableSynProduct) {
            throw ServiceExceptionUtil.exception(ES_PRODUCT_DEFAULT_ERROR, "未打开同步eSim商品");
        }

        // 查询第三方
//        final ProductRes productRes = simThirtyApiService.queryProduct();
//        final List<ProductRes.Product> apiProducts = productRes.getProducts();
//        for (ProductRes.Product apiProduct : apiProducts) {
//            final String[] country = apiProduct.getCountry().split(";");
//            if (country.length > 1) {
//                apiProduct.setType(EsProductTypeEnum.AREA.getValue());
//            } else {
//                apiProduct.setType(EsProductTypeEnum.COUNTRY.getValue());
//            }
//        }

        // 填充测试数据
        final List<ProductRes.Product> testProducts = attachTestProduct();

        final List<ProductRes.Product> products = new ArrayList<>();
//        products.addAll(apiProducts);
        products.addAll(testProducts);

        int productCount = 0;
        for (ProductRes.Product product : products) {
            final String id = product.getId();

            // 查询product
            EsProductDO esProduct = getEsProduct(id);

            final boolean existed = esProduct != null;
            if (!existed) {
                esProduct = new EsProductDO();
                esProduct.setId(id);
            }
            esProduct.setName(product.getName());
            final String packageInfo = product.getPackageInfo();
            esProduct.setPackageInfo(packageInfo);

            final int[] packageInfoArr = ESimUtil.parseDataAndValidity(packageInfo);
            esProduct.setDataAllowanceMb(packageInfoArr[0]);
            esProduct.setValidityPeriodDays(packageInfoArr[1]);
            esProduct.setDescription(product.getDescription());
            esProduct.setCountry(product.getCountry());
            esProduct.setType(product.getType());

            if (existed) {
                esProductMapper.updateById(esProduct);
            } else {
                esProductMapper.insert(esProduct);
            }

            productCount++;
        }

        log.info("从api同步产品-成功, productCount = {}", productCount);
    }

    // 填充测试数据
    private List<ProductRes.Product> attachTestProduct() {
        final List<ProductRes.Product> products = new ArrayList<>();

        final String jsonString = FileUtil.readString("E:/esim/es_product.json", "utf-8");
        final Map<String, List<String>> map = JsonUtils.parseObject(jsonString, Map.class);
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            final String groupName = entry.getKey();
            final List<String> countryNameList = entry.getValue();

            final int skuNum = RandomUtil.randomInt(1, 10);
            for (int i = 0; i < skuNum; i++) {
                final ProductRes.Product product = new ProductRes.Product();
                product.setName(groupName);
                product.setCountry(String.join(";", countryNameList));
                final List<Integer> mbList = Arrays.asList(1024, 1024 * 5, 1024 * 30, 1024 * 50);
                final int mb = mbList.get(RandomUtil.randomInt(0, mbList.size() - 1));
                final int day = RandomUtil.randomInt(1, 60);
                final String packageInfo = String.format("%sMB/%sday", mb, day);
                product.setPackageInfo(packageInfo);
                if (countryNameList.size() > 1) {
                    // area
                    product.setType(EsProductTypeEnum.AREA.getValue());
                } else {
                    // country
                    product.setType(EsProductTypeEnum.COUNTRY.getValue());
                }

                product.setId(new Digester(DigestAlgorithm.MD5).digestHex(product.toString()));
                products.add(product);
            }
        }

        return products;
    }
}